package com.LC.Service.Impl;

import com.LC.DAO.RoleDAO;
import com.LC.Entity.PageResult;
import com.LC.Entity.QueryPageBean;
import com.LC.Entity.Role;
import com.LC.Service.RoleService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
  
    @Autowired
    private RoleDAO roleDAO;
  
  
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        //使用mybatis分页助手
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> rolePage = roleDAO.findPage(queryString);
        PageResult pageResult = new PageResult(rolePage.getTotal(),rolePage.getResult());
        return pageResult;
    }
    
    @Override
    public void addRole(Integer[] permissionIds, Role addRole) {
        try {
            roleDAO.addRole(addRole);
            Integer roleId = addRole.getId();
            if (permissionIds.length > 0){
                for (Integer permissionId : permissionIds) {
                    roleDAO.addTot_role_permission(roleId,permissionId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Role getRoleById(int id) {
        Role roleById = roleDAO.getRoleById(id);
        return roleById;
    }

    @Override
    public List<Integer> getPermissionIdsByRoleId(int id) {
        List<Integer> permissionIdsByRoleId = roleDAO.getPermissionIdsByRoleId(id);
        return permissionIdsByRoleId;
    }

    @Override
    public void upDateRole(Integer[] permissionIds, Role upDateRole) {
        try {
            roleDAO.updateRole(upDateRole);
            roleDAO.deleteT_role_permissionByRoleId(upDateRole.getId());
            if (permissionIds.length > 0){
                for (Integer permissionId : permissionIds) {
                    roleDAO.addTot_role_permission(upDateRole.getId(),permissionId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteRole(int id) {
        try {
            roleDAO.deleteT_role_permissionByRoleId(id);
            roleDAO.deleteRole(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
